package jsu.blogger.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import jakarta.servlet.http.HttpServletRequest;
import jsu.blogger.filter.DataFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.*;

public class DataFilterUtil {

    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final Map<String, String[]> expectedParameters = new HashMap<>();
    private static final Logger log = LoggerFactory.getLogger(DataFilter.class);
    static {
        // 定义不同消息类型的期望参数
        expectedParameters.put("login", new String[]{"email", "password","currentDevice"});
        expectedParameters.put("register", new String[]{"email", "password","code"});
        expectedParameters.put("getUsername", new String[]{"userId"});
        expectedParameters.put("getUserInterest", new String[]{"userId"});
        expectedParameters.put("getOtherUserData", new String[]{"userId"});
        expectedParameters.put("interestsAlter", new String[]{"userId","newInterests"});
        expectedParameters.put("getUserAvatar", new String[]{"userId"});
        expectedParameters.put("test", new String[]{"test1", "test2"});
        expectedParameters.put("getEmailVerifyCode", new String[]{"email"});
        expectedParameters.put("setUsername", new String[]{"userId", "newUsername"});
        expectedParameters.put("setSex", new String[]{"userId", "sex"});
        expectedParameters.put("setAvatar", new String[]{"userId","avatar"});
        expectedParameters.put("getUserFollowing", new String[]{"userId","currentPage","pageSize"});
        expectedParameters.put("creatFolder", new String[]{"userId", "folderName"});
        expectedParameters.put("getFavorites", new String[]{"userId"});
        expectedParameters.put("deleteLive", new String[]{"postId","uid"});
        expectedParameters.put("getRecommendedBlogs", new String[]{"count","offset"});
        expectedParameters.put("publishLive", new String[]{"uid","createdAt","text"});
        expectedParameters.put("searchPost", new String[]{"searchContent","currentPage","pageSize"});
        expectedParameters.put("getEmail", new String[]{"userId"});
        expectedParameters.put("changeAccount", new String[]{"email", "code"});
        expectedParameters.put("searchUser", new String[]{"searchContent","currentPage","pageSize"});
        expectedParameters.put("getChooseInterests", new String[]{"userId"});
        expectedParameters.put("getUserPosts", new String[]{"userId","currentPage","pageSize"});
        expectedParameters.put("setEmail", new String[]{"userId", "email"});
        expectedParameters.put("searchDraft", new String[]{"draftId","userId","resourceId"});
        expectedParameters.put("saveDraft", new String[]{"draftId","userId","title","resourceId","content", "coverOption","description","articleType", "originalUrl", "saveedTags", "type"});
        expectedParameters.put("getBlogInteractiveData",new String[]{ "blogId" ,"userId","authorId"});
        expectedParameters.put("blogLikeOrDisLike",new String[]{ "userId","postId","isLike"});
        expectedParameters.put("removeUserLikeOrDislike",new String[]{ "userId","postId"});
        expectedParameters.put("processingCollection",new String[]{ "userId","postId","folderList"});
        expectedParameters.put("selectFavorites",new String[]{ "userId","postId","offset","count"});
        expectedParameters.put("newFavorites",new String[]{ "userId","newFolderName","isDefault","isPublic","folderDescription"});
        expectedParameters.put("searchUserAllBlogs",new String[]{ "userId","offset","count"});
        expectedParameters.put("deleteBlog",new String[]{ "userId","postId"});
        expectedParameters.put("searchUserAllDrafts",new String[]{ "userId","offset","count"});
        expectedParameters.put("deleteDraft",new String[]{ "userId","draftId"});
        expectedParameters.put("setComment", new String[]{"postId","userId","parentCommentId","replyToUserId","content","createdAt"});
    }

    // 读取请求体
    public static String readRequestBody(HttpServletRequest request) {
        StringBuilder requestBody = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                requestBody.append(line);
            }
        } catch (IOException e) {
            System.out.println("请求体读取异常！");
            throw new RuntimeException(e);
        }
        return requestBody.toString();
    }

    // 解析请求体为键值对
    public static Map<String, Object> parseRequestBody(String requestBody) {
        Map<String, Object> requestBodyMap = new HashMap<>();
        try {
            requestBodyMap = objectMapper.readValue(requestBody, new TypeReference<Map<String, Object>>() {});
        } catch (IOException e) {
            System.out.println("请求体解析异常！");
            throw new RuntimeException(e);
        }
        return requestBodyMap;
    }

    // 数据合法校验
    public static List<String> validateData(String msgType, Map<String, Object> data) {
        List<String> errors = new ArrayList<>();
        String[] requiredFields = expectedParameters.get(msgType);

        if (requiredFields == null) {
            errors.add("未知的消息类型: " + msgType);
            return errors;
        }

        // 收集所有缺失的字段
        for (String field : requiredFields) {
            if (!data.containsKey(field)) {
                errors.add("缺失字段: " + field);
            }
        }

        // 检查多余字段
        for (String key : data.keySet()) {
            if (!Arrays.asList(requiredFields).contains(key)) {
                errors.add("多余字段: " + key);
            }
        }

        return errors; // 返回所有错误信息的列表
    }

}
